import { PageContainer } from '@ant-design/pro-layout';
import { Button, message,Popconfirm, Select,Form, Table} from 'antd';
import { FormattedMessage } from 'umi';
import ProTable from '@ant-design/pro-table';

import { DrawerForm,ProFormText,ProFormSelect} from '@ant-design/pro-form';
import React, { useState, useRef} from 'react';
import type { ProColumns,ActionType } from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import {UserType} from '../../../model';
import {userListData,roleListData,saveUser,updateUser,deleteUser,updateUserFactory} from '../service';
import { useEffect } from 'react';
import { Space } from 'antd';

const { Option } = Select;

export default () => {

  const [showCreate, setShowCreate] = useState(false);
  const [currentUser,setCurrentUser] = useState(undefined);
  const [factoryData,setFactoryData] = useState<any>([])
  const [chooseFactory,setChooseFactory] = useState<any>([])
  const formRef = useRef();
  const [roleList,setRoleList] = useState<any>([])
  const [roleList2,setRoleList2] = useState<any>([])

  const [editFlag,setEditFlag] = useState(false);
  const actionRef =useRef<ActionType>();
  //表头信息以及表值设置
  const columns: ProColumns<UserType>[] = [
    {
      title:'用户名',
      dataIndex: 'loginname',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title:'名称',
      dataIndex: 'name',
      ellipsis:true,
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: '授权厂家',
      dataIndex: 'factoryList',
      hideInSearch:true,
      renderText:(_,record:any)=>{
        return record.factoryList.map((item:any)=>item.shortName).join(',')
      }
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width:150,
      ellipsis:true,
      hideInSearch:true,
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch:true,
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
     },
    {
      title: '角色',
      dataIndex: 'roleName',
      valueType:'select',
      valueEnum:()=>{
        var obj = {};
         roleList2.reduce(function (item: any, next: any) {
          if (!obj[next.label]) {
            obj[next.label] = {
              text: next.label
            };
            item.push(next);
          }
          return item;
        }, []);
        return obj
      },
      // hideInSearch:true,
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }]
        };
      },
    },
    {
      title: "操作",
      valueType: 'option',
      render: (text, record:any,_, action) => {
        // if(record.roleName==='管理员'){
        //   return [];
        // }
        return [
          <a
            key="editable"
            onClick={() => {
              record.factoryIds = record.factoryList.map((item:any)=>item.id)
              setCurrentUser(record);
              record.roleId = record.rolesList[0].roleId;
              formRef.current.setFieldsValue(record);
              setShowCreate(true);
              setEditFlag(!(record.roleName.indexOf('客户')>=0||record.roleName.indexOf('销售')>=0))
            }}
          >
            编辑
          </a>,
           <Popconfirm title="确定删除该用户吗?" key="delete" onConfirm={async () => {
            var val = await deleteUser({"id":record.id});
            if(val.errorCode==='200'){
              actionRef.current?.reloadAndRest?.();
              message.success('提交成功');
              return true;
            }else{
              message.success(val.errorMessage);
              return false;
            }
           }}>
           <a hidden={record.roleName.indexOf('客户')>=0||record.roleName.indexOf('销售')>=0}>删除</a>
         </Popconfirm>
        ]
      }
    },
  ];

  useEffect(() => {
    initRole();
    return function cleanup() {};
  }, []);

  const initRole = async()=>{
    var val = await roleListData();
    var data = val.data;
    var result:any[]=[];
    var result2:any[]=[];
    data.forEach((element:any) => {
      const item:any = {}
      item.label=element.name;
      item.value=element.id;
      if(element.name.indexOf('客户')==-1&&element.name.indexOf('销售')==-1&&element.name.indexOf('管理员')==-1){
        result.push(item);
      }
      result2.push(item);

    });
    setRoleList(result)
    setRoleList2(result2)
}

  return (
    <PageContainer>
    <ProTable<UserType>
      tableAlertOptionRender={({selectedRowKeys,onCleanSelected}) => {
        return (
          <Space size={16}>
            <a key='i2' style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <Form.Item style={{marginBottom:5,maxWidth:200,minWidth:200}}>
            <Select  mode="multiple" placeholder="请选择" defaultValue={[]}
                  style={{ width: '100%' }}
                  onChange={(value)=>{
                    setChooseFactory(value)
                  }}
                  allowClear>
                    {factoryData.map((item:any)=>{
                      return <Option value={item.value} key={item.value}>{item.label}</Option>
                    })}
                  </Select>
            </Form.Item>
            <a key='i1' onClick={async()=>{
                var val = await updateUserFactory({'ids':selectedRowKeys.join(','),'factoryIds':chooseFactory.join(',')})
                if(val.errorCode==='200'){
                  actionRef.current?.reloadAndRest?.();
                  message.success('提交成功');
                  return true;
                }else{
                  message.success(val.errorMessage);
                  return false;
                }
              }}>设置厂家</a>
          </Space>
        );
      }}
      rowSelection={{
        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      }}
      headerTitle='用户列表'
      actionRef={actionRef}
      request={async(params, sorter, filter) => userListData({...params,filter}).then(res=>{
        setFactoryData(res.data.factoryList.map((item:any)=>{return {label:item.shortName,value:item.id}}))
        res.data=res.data.userList;
        return res;
      })}
      columns={columns}
      rowKey="id"
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      search={{
        labelWidth: 120,
      }}
      toolBarRender={() => [
        <Button
          type="primary"
          key="primary"
          onClick={() => {
            setEditFlag(true)
            setShowCreate(true);
          }}
        >
          <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
        </Button>,
      ]}
      toolbar={{settings:[]}}
      />

         <DrawerForm
           title="用户创建"
           onVisibleChange={(v)=>{
            setShowCreate(v);
            if(!v){
              setCurrentUser(undefined);
            }
           }}
           visible={showCreate}
           drawerProps={{
             destroyOnClose:true,
             forceRender:true
           }}
           formRef={formRef}
           onFinish={async (values: any) => {
              var val ;
              if(values.factoryIds&&values.factoryIds.length>0){
                values.factoryIds = values.factoryIds.join(",")
              }
              if(currentUser){
                values.id=currentUser?.id;
                val = await updateUser(values)
              }else{
                val = await saveUser(values)
              }
              if(val.errorCode==='200'){
                actionRef.current?.reloadAndRest?.();
                message.success('提交成功');
                return true;
              }else{
                message.success(val.errorMessage);
                return false;
              }
           }}
          
         >
          <ProFormText  disabled={!editFlag} name="loginname" label="登录名"  placeholder="请输入登录名"
                rules={[
                  {
                    required: true,
                  },
                ]}/>
          <ProFormText.Password disabled={!editFlag} name="password" label="密码" placeholder="请输入密码"  
                />
          <Form.Item
                  name="factoryIds"
                  label="授权厂家"
                  style={{width:'440px'}}
                >
                  <Select  mode="multiple"
                    style={{ width: '100%' }}
                    onChange={(value)=>{
                      console.log(value)
                    }}
                    allowClear>
                      {factoryData.map((item:any)=>{
                        return <Option value={item.value} key={item.value}>{item.label}</Option>
                      })}
                    </Select>
              </Form.Item>
           <ProFormText  name="name" disabled={!editFlag} label="用户名"  placeholder="请输入用户名"
                rules={[
                  {
                    required: true,
                  },
                ]}/>
           <ProFormSelect  name="roleId" disabled={!editFlag} label="角色" placeholder="请选择用户角色"
                rules={[
                  {
                    required: true,
                  },
                ]}
                options={roleList}
               />
           <ProFormText  name="email" disabled={!editFlag} label="邮箱" placeholder="请输入邮箱" 
                rules={[
                  {
                    required: true,
                  },
                  {
                    pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                    message: '邮箱格式不正确',
                  },
                ]}/>
           <ProFormText  name="phone" disabled={!editFlag} label="手机号码" placeholder="请输入手机号码"
                rules={[
                 
                  
                ]} />
            <ProFormSelect name="isEmail" disabled={!editFlag} label="推送标识" options={[{
                    value: 0,
                    label: '无',
                  },
                  {
                    value: 1,
                    label: '有',
                  },]}/>
         </DrawerForm>
  </PageContainer>
  );
};